/*
 * 版权所有(c) 刘定成(1952110078@qq.com)  2022 - 2022
 */

package com.ldc.commonlibs.common;

import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ldc.commonlibs.utils.CollectionsUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liudc
 * @since 2022/7/4 00:04
 */
public abstract class RecyclerAdapterBase<T> extends RecyclerView.Adapter<RecyclerViewHolder> {
    private final List<T> mData = new ArrayList<>();
    private @LayoutRes
    int layoutId;

    public RecyclerAdapterBase(int layoutId) {
        this.layoutId = layoutId;
    }

    protected List<T> getData() {
        return mData;
    }

    /**
     * 添加新数据
     *
     * @param data 列表
     */
    public void addNewData(List<T> data) {
        mData.clear();
        if (CollectionsUtil.isNotEmpty(data)) {
            mData.addAll(data);
        }
        notifyDataSetChanged();
    }

    /**
     * 添加数据
     *
     * @param data 列表
     */
    public void addData(List<T> data) {
        mData.clear();
        if (CollectionsUtil.isNotEmpty(data)) {
            if (!mData.containsAll(data)) {
                mData.addAll(data);
            }
        }
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return RecyclerViewHolder.getLayoutView(layoutId, parent, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
        T data = mData.get(position);
        if (data != null) {
            convertData(holder, data, position);
        }
    }

    @Override
    public int getItemCount() {
        return CollectionsUtil.isEmpty(mData) ? 0 : mData.size();
    }

    protected abstract void convertData(RecyclerViewHolder holder, T data, int position);
}
